package cn.wen.core.titlebar.base;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * APP标题抽象基类
 */

public abstract class BaseTitleBar<B extends BaseBarBuild> implements IBar {
    /**
     * 标题加载的View
     */
    private View mTitleBar;
    /**
     * 构建器
     */
    protected B build;

    public BaseTitleBar(B build) {
        this.build = build;
    }

    @Override
    public abstract int getBarLayoutId();

    @Override
    public void apply() {
        // 标题添加到哪个父布局
        ViewGroup parent = build.mParent;
        if (parent == null && build.mActivity != null) {
            // 如果用户不写，默认添加到根布局DecorView布局（FrameLayout-->LinearLayout）
            ViewGroup decorView = (ViewGroup) build.mActivity.getWindow().getDecorView();
            parent = (ViewGroup) decorView.getChildAt(0);// LinearLayout
        }
        if (parent == null) {
            return;
        }
        mTitleBar = LayoutInflater.from(build.mActivity).inflate(getBarLayoutId(), parent, false);
        parent.addView(mTitleBar, 0);
        // 设置自定义文本
        int textSize = build.mTexts.size();
        for (int i = 0; i < textSize; i++) {
            setText(build.mTexts.keyAt(i), (CharSequence) build.mTexts.valueAt(i));
        }
        // 设置自定义点击事件
        int clickSize = build.mClicks.size();
        for (int i = 0; i < clickSize; i++) {
            setOnClickListener(build.mClicks.keyAt(i), (View.OnClickListener) build.mClicks.valueAt(i));
        }
        applyParams(build);
    }

    /**
     * 子类实现具体的构建参数
     */
    protected abstract void applyParams(B build);


    /**
     * 设置View的文本
     */
    protected void setText(int viewId, CharSequence text) {
        TextView tv = findViewById(viewId);
        if (tv != null && !TextUtils.isEmpty(text)) {
            tv.setVisibility(View.VISIBLE);
            tv.setText(text);
        } else {
            if (tv != null) {
                tv.setText("");
            }
        }
    }

    /**
     * 设置点击事件
     */
    protected void setOnClickListener(int viewId, View.OnClickListener listener) {
        View view = findViewById(viewId);
        if (view != null) {
            view.setOnClickListener(listener);
        }
    }

    /**
     * 查找标题栏里面的控件
     */
    public <T extends View> T findViewById(int viewId) {
        return (T) mTitleBar.findViewById(viewId);
    }

    public View getTitleBar() {
        return mTitleBar;
    }
}
